package com.sanerzone.smscenter.gateway.http.handler.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sanerzone.smscenter.biz.message.SMSMOMessage;
import com.sanerzone.smscenter.biz.message.SMSMTMessage;
import com.sanerzone.smscenter.biz.message.SMSRTMessage;
import com.sanerzone.smscenter.biz.message.SMSSRMessage;
import com.sanerzone.smscenter.biz.utils.UnicodeUtil;
import com.sanerzone.smscenter.common.tools.HttpRequest;
import com.sanerzone.smscenter.gateway.http.handler.GateWayHttpAbstract;
import com.sanerzone.smscenter.gateway.http.message.SmsHttpMsgResponse;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 找客互联
 */
public class SmsApiZKHL extends GateWayHttpAbstract
{

    public SmsApiZKHL(String gateWayID, String jsonParams)
    {
        super(gateWayID, jsonParams);
    }

    @Override
    public List<SMSSRMessage> doSend(SMSMTMessage mt) {
        Map<String,Object> params = Maps.newHashMap();

        params.put("account", paramsMaps.get("account"));
        params.put("password", paramsMaps.get("password"));
        params.put("mobile", mt.getPhone());
        try {
            params.put("content", URLEncoder.encode(mt.getSmsContent(),"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            logger.error("提交网关短信内容utf-8编码错误，网关:{}, 短信内容:{}", this.gateWayID, mt.getSmsContent());
        }
        params.put("extend", paramsMaps.get("extend"));
        String result =  HttpRequest.sendPost(paramsMaps.get("apiUrl") + "/api/sms/send", Joiner.on("&").withKeyValueSeparator("=").join(params), null);
        
        logger.info("网关:{}, 请求:{}, 响应:{}", this.gateWayID, params.toString(), result);

        List<SMSSRMessage> resultList = Lists.newArrayList();

        SMSSRMessage message = initGatewayResultMessage(result, mt, "code");
        String resultCode = null;
        String resultMessage = null;
        String taskid = null;
            JSONObject object = JSON.parseObject(result);
            if(StringUtils.equals(message.getResult(), "F10199")) {
                resultCode = object.getString("code");
                resultMessage = object.getString("errorMsg");
                if(StringUtils.equals(resultCode, "0")) {
                    taskid = object.getString("taskId");
                }
                message.setMsgkey(mt.getPhone());
                setGatewayResultCode(message, taskid, resultCode, resultMessage, "0");
                resultList.add(message);
            }
        return resultList;
    }
    
    @Override
    public SmsHttpMsgResponse parseReport(String text, List<SMSRTMessage> rtList)
    {
        if (StringUtils.isNotBlank(text)) {
            JSONObject data = JSON.parseObject(text);
                logger.info("{}网关推送状态报告:{}", gateWayID, text);
                SMSRTMessage smsRtMessage = initSmsRtMessage(data.getString("taskId"), data.getString("mobile"), data.getString("mobile"),
                    data.getString("code"), "0");
                rtList.add(smsRtMessage);
        }
        return new SmsHttpMsgResponse("success");
    }

    @Override
    public SmsHttpMsgResponse parseDeliver(String text, List<SMSMOMessage> moList)
    {
        SmsHttpMsgResponse smsHttpMsgResponse = new SmsHttpMsgResponse("0");
        if (StringUtils.isNotBlank(text)) {
            logger.info("{}网关推送用户上行:{}", gateWayID, text);
            JSONObject data = JSON.parseObject(text);
            SMSMOMessage sMSMOMessage = new SMSMOMessage();
            sMSMOMessage.setGateWayID(gateWayID);
            sMSMOMessage.setMsgContent(UnicodeUtil.decode(data.getString("content")));
            sMSMOMessage.setPhone(data.getString("mobile"));
            sMSMOMessage.setSenttime(data.getString("moTime"));
//                sMSMOMessage.setSpnumber(String.valueOf(resultMap.get("srcid")));
            sMSMOMessage.setUuid(UUID.randomUUID().toString());
            moList.add(sMSMOMessage);
        }
        return smsHttpMsgResponse;
    }

    @Override
    public String queryReport(String jsonText) {
        return "";
    }

    @Override
    public String queryDeliver(String jsonText) {
        return "";
    }

    /**
     *
     * userid 用户名
     * account 账号
     * password 密码
     * action 任务名称 固定值overage
     * @return
     */
    public String balance()
    {
        Map<String,Object> params = Maps.newHashMap();
        return "没有余额查询接口";
    }
    
    public static void main(String[] args)
    {
        String params = "{\"account\":\"180427719\",\"password\":\"k7T5UgZSJ3\",\"extend\":\"\",\"apiUrl\":\"http://api.vnetpower.cn\"}";

        SmsApiZKHL api = new SmsApiZKHL("ZY",params);
//        String balance = api.balance();
        SMSMTMessage message = new SMSMTMessage();
        message.setPhone("18368493887");
        message.setId("test123456");
        message.setSmsContent("【等都科技】你的短信验证码是432446");
        api.doSend(message);
//        api.queryDeliver("");
    }
    
}